package com.daoshu.socket.utils;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2017/9/6.
 */
@Slf4j
public class MD5Util {


    private MD5Util() {
        throw new IllegalStateException("Utility class");
    }


    /**
     * md5加密算法
     *
     * @param originString
     * @return
     */
    public static String encodeByMD5(String originString) {
        return md5(originString, Charset.defaultCharset());
    }


    public static String md5(String input, Charset charset) {
        MessageDigest md = null;

        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException var9) {
            log.error("md5 err:" + var9.getMessage());
            return null;
        }

        md.update(input.getBytes(charset));
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        byte[] tmp = md.digest();
        char[] str = new char[32];
        int k = 0;

        for (int i = 0; i < 16; ++i) {
            byte byte0 = tmp[i];
            str[k++] = hexDigits[byte0 >>> 4 & 15];
            str[k++] = hexDigits[byte0 & 15];
        }

        return String.valueOf(str);
    }
}
